package org.ttitfly.ttcore.entity.account;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.ttitfly.ttcore.entity.IdEntity;
import org.ttitfly.ttcore.entity.menu.SystemMenu;

/**
 * 角色.
 * 
 * 注释见{@link User}.
 * 
 * @author calvin
 */
@Entity
@Table(name = "ACCT_ROLE")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role extends IdEntity {

	private String name;
	
	private List<SystemMenu> menus = new ArrayList<SystemMenu>();
	
	private List<Resource> resources = new ArrayList<Resource>();
	
	
	private List<User> users = new ArrayList<User>();
	

	public Role() {

	}

	public Role(Long id, String name) {
		this.id = id;
		this.name = name;
	}

	@Column(nullable = false, unique = true)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	
	@ManyToMany(targetEntity = SystemMenu.class, cascade = { CascadeType.PERSIST,CascadeType.MERGE } )
	@JoinTable(name = "ACCT_Role_System_Menu", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "system_menu_id") } , 
			uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", "system_menu_id" }))
    @OrderBy(value = "orderNum ASC")
	public List<SystemMenu> getMenus() {
		return menus;
	}

	public void setMenus(List<SystemMenu> menus) {
		this.menus = menus;
	}
	@ManyToMany(targetEntity = Resource.class, cascade = { CascadeType.PERSIST,CascadeType.MERGE })
	@JoinTable(name = "ACCT_Role_resource", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "resource_ID") } , 
			uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", "resource_ID" }))
	public List<Resource> getResources() {
		return resources;
	}

	public void setResources(List<Resource> resources) {
		this.resources = resources;
	}

	
	@ManyToMany(mappedBy="roles")
	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
